# -*- coding: utf-8 -*-

'''eof
name:最近一年订烟额增长率（LT）
code:Mon12MoneyRate_LT
tableName:
columnName:
groups:烟商
dependencies:BTM
type:常用指标
datasourceType:在线指标
description:
eof'''

'''
计算增长率时，剔除0左右两个增长率的的计算
以0为分界点，将list进行分隔，分别计算增长率，
最后取平均
T1:回推1个月 T2：回推2个月 .... T12：回推的12个月
'''
import sys
import pandas as pd
import datetime
import numpy as np

reload(sys)
sys.setdefaultencoding('utf-8')



def Mon12MoneyRate_LT():
    null_type_list = ['', None, 'null', 'Null', '/', ' ']
    money_month = { 'T12':[],'T11':[],'T10':[],'T9':[],'T8':[],'T7':[],'T6':[],
                   'T5':[],'T4':[],'T3':[],'T2':[],'T1':[] }
    sum_money = []
    try:
        BTM_ = BTM['data']
        if Formate(BTM_.get('bbd_dotime')) is not None:
            ApplTime = datetime.datetime.strptime(Formate(BTM_['bbd_dotime']), '%Y%m%d')
            last_year_days_list = [
                (ApplTime - pd.tseries.offsets.DateOffset(days=i * 30)).strftime('%Y%m%d') \
                for i in xrange(12, -1, -1)]
        else:
            last_year_days_list = [
                (datetime.datetime.now() - pd.tseries.offsets.DateOffset(days=i * 30)).strftime('%Y%m%d') \
                for i in xrange(12, -1, -1)]
    except:
        return u'缺失值'

    try:
        if BTM_.has_key('indent') and BTM_['indent'] not in null_type_list \
            and len(BTM_['indent']) >=1:
            for i in BTM_['indent']:
                if i.has_key('indentMoney') and i['indentMoney'] not in null_type_list \
                    and isfloat(i['indentMoney']) \
                        and i.has_key('indentDate') and i['indentDate'] not in null_type_list \
                        and Formate(i['indentDate']) is not None:
                    if Formate(i['indentDate']) > last_year_days_list[0] and Formate(i['indentDate']) <= last_year_days_list[1]:
                        money_month['T12'].append(float(i['indentMoney']))
                    elif Formate(i['indentDate']) > last_year_days_list[1] and Formate(i['indentDate']) <= last_year_days_list[2]:
                        money_month['T11'].append(float(i['indentMoney']))
                    elif Formate(i['indentDate']) > last_year_days_list[2] and Formate(i['indentDate']) <= last_year_days_list[3]:
                        money_month['T10'].append(float(i['indentMoney']))
                    elif Formate(i['indentDate']) > last_year_days_list[3] and Formate(i['indentDate']) <= last_year_days_list[4]:
                        money_month['T9'].append(float(i['indentMoney']))
                    elif Formate(i['indentDate']) > last_year_days_list[4] and Formate(i['indentDate']) <= last_year_days_list[5]:
                        money_month['T8'].append(float(i['indentMoney']))
                    elif Formate(i['indentDate']) > last_year_days_list[5] and Formate(i['indentDate']) <= last_year_days_list[6]:
                        money_month['T7'].append(float(i['indentMoney']))
                    elif Formate(i['indentDate']) > last_year_days_list[6] and Formate(i['indentDate']) <= last_year_days_list[7]:
                        money_month['T6'].append(float(i['indentMoney']))
                    elif Formate(i['indentDate']) > last_year_days_list[7] and Formate(i['indentDate']) <= last_year_days_list[8]:
                        money_month['T5'].append(float(i['indentMoney']))
                    elif Formate(i['indentDate']) > last_year_days_list[8] and Formate(i['indentDate']) <= last_year_days_list[9]:
                        money_month['T4'].append(float(i['indentMoney']))
                    elif Formate(i['indentDate']) > last_year_days_list[9] and Formate(i['indentDate']) <= last_year_days_list[10]:
                        money_month['T3'].append(float(i['indentMoney']))
                    elif Formate(i['indentDate']) > last_year_days_list[10] and Formate(i['indentDate']) <= last_year_days_list[11]:
                        money_month['T2'].append(float(i['indentMoney']))
                    elif Formate(i['indentDate']) > last_year_days_list[11] and Formate(i['indentDate']) <= last_year_days_list[12]:
                        money_month['T1'].append(float(i['indentMoney']))
                    else:
                        pass
            keys = sorted(money_month,key=lambda x:int(x[1:]))
            for k in keys:
                if money_month[k] == []:
                    return u'缺失值'
                else:
                    sum_money.append(sum(money_month[k]))
            ratio = cal_ratio(sum_money)
            if ratio != []:
                return round(np.mean(ratio), 4)
            else:
                return u'缺失值'
        else:
            return u'缺失值'
    except:
        return u'缺失值'


def cal_ratio(list):
    ratio = []
    index_0 = [i for i,v in enumerate(list) if v==0.0]
    if len(index_0) ==1:
        tmp1 = list[0:index_0[0]]
        tmp2 = list[index_0[0] + 1:]
        if len(tmp1) >= 2:
            for j in xrange(len(tmp1) - 1):
                ratio.append((float(tmp1[j]))/(float(tmp1[j+1])) - 1)
        if len(tmp2) >= 2:
            for j in xrange(len(tmp2) - 1):
                ratio.append(float(tmp2[j])/float(tmp2[j+1]) - 1)
        return ratio
    elif len(index_0) >1:
        for i,v in enumerate(index_0):
            if i == 0:
                tmp = list[0:v]
                if len(tmp) >= 2:
                    for j in xrange(len(tmp)-1):
                        ratio.append((float(tmp[j])/float(tmp[j+1]))-1)

            elif i > 0 and i < (len(index_0)-1):
                tmp = list[index_0[i-1]+1:v]
                if len(tmp) >= 2:
                    for j in xrange(len(tmp)-1):
                        ratio.append(float(tmp[j])/float(tmp[j+1])-1)
            elif i == (len(index_0) -1):
                tmp1 = list[v+1:]
                tmp2 = list[index_0[i-1]+1:v]
                if len(tmp1) >= 2:
                    for j in xrange(len(tmp1)-1):
                        ratio.append(float(tmp1[j])/float(tmp1[j+1])-1)
                if len(tmp2) >=2:
                    for j in xrange(len(tmp2)-1):
                        ratio.append(float(tmp2[j])/float(tmp2[j+1])-1)
            else:
                pass
        return ratio
    else:
        for j in xrange(len(list)-1):
            ratio.append(float(list[j]/list[j+1])-1)
        return ratio

def isfloat(x):
    try:
        if isinstance(float(x), float) and float(x)>=0:
            return True
        else:
            return False
    except:
        return False

#统一时间格式为'20180528'-> '%Y%m%d'
def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date

    
result = Mon12MoneyRate_LT()



